<!--
 * @Date: 2023-03-23 11:10:57
 * @LastEditTime: 2023-04-14 14:14:30
 * @FilePath: /nlk/src/views/home/components/applyBuy.vue
 * 介绍:立即申购
-->
<script lang="ts" setup>
import Rdialog from "@@/components/rework/Rdialog";
import router from "@@/router";
import { HomeData } from "@@/api/page/home";
import useBalanceStore from "@@/store/useBalanceStore";
import toast from "@@/hooks/toast";
import * as web3Eth from "@@/sdk/web3Eth";
import { formatNumber } from "@@/utils/tools/tools";
import { apiApplyBuyTxid } from "@@/api/module/transaction";
import { checkAuth } from "@@/hooks/sysHooks";
import { apiApplyBuyGameBalance } from "@@/api/page/home";
import { showDialog } from "vant";
import { removeCache } from "@@/hooks/routeCache";

const { t } = useI18n();
const RdialogRef = ref<InstanceType<typeof Rdialog>>();
const formData = reactive({
  optionIndex: 0,
  amount: "",
});

async function onSubmitBtn() {
  const amount = Number(formData.amount);
  const currentOption = goods.value?.store[formData.optionIndex];
  const max = Number(currentOption?.max);
  const min = Number(currentCoinMin.value);
  const coin = currentCoin.value!;
  if (!(amount <= max))
    return toast.text(`${t("bu-neng-da-yu")}: ${max}${coin.code}`);
  if (!(amount >= min))
    return toast.text(`${t("bu-neng-xiao-yu")}: ${min}${coin.code}`);
  checkAuth(coin).then(async () => {
    toast.loading();
    const balance = await balanceStore.findBalance(coin);
    toast.close();
    if (!(amount <= balance!)) return toast.text(t("yu-e-bu-zu"));
    applyBuy(coin, amount, currentOption!);
  });
}
/**申购 */
async function applyBuy(
  coin: CoinInfo,
  amount: number,
  option: HomeData.GoodsOption
) {
  toast.loading();
  const res = await web3Eth.sdkAutoTransfer(
    coin.contract_addr,
    amount,
    coin.format,
    toAddress
  );
  toast.close();
  if (!res.status) return toast.error(res.message || "fail");
  await apiApplyBuyTxid({
    txid: res.data!,
    store_id: option.id,
    number: amount,
    coin_id: option.coin_id,
  });
  removeCache("fundManage");
  router.push({ name: "buySuccess" });
}
defineExpose({ open });
/**当前购买商品 */
const goods = ref<HomeData.StoreItem>();
//* 当渲染不同产品时
watch(goods, () => {
  formData.amount = "";
  formData.optionIndex = 0;
});
/**收款地址 */
let toAddress: string;

function open(currentGoods: HomeData.StoreItem, address: string) {
  toAddress = address;
  goods.value = currentGoods;
  const coin = coinEnum.value[goods.value.code];
  balanceStore.findBalance(coin!);
  balanceStore.findGameBalance(coin!);
  RdialogRef.value?.open({
    showNoBtn: false,
    title: t("li-ji-shen-gou"),
  });
}
const balanceStore = useBalanceStore();
const { coinEnum } = storeToRefs(balanceStore);
const currentCoin = computed(() => coinEnum.value[goods.value?.code!]);
const currentOption = computed(() => goods.value?.store[formData.optionIndex]);
// const yearMultipe = computed(() => {
//   if (!currentOption.value) return 0;
//   const day = currentOption.value.day;
//   const multipe = currentOption.value.multiple;
//   const dayMultipe = Number(multipe) / day;
//   return dayMultipe * 360;
// });
/**点击购买理财产品,通过游戏余额 */
function onSubmitBtnByGameBalance() {
  const amount = Number(formData.amount);
  const currentOption = goods.value?.store[formData.optionIndex];
  const max = Number(currentOption?.max);
  const min = Number(currentCoinMin.value);
  const coin = currentCoin.value!;
  if (!(amount <= max))
    return toast.text(`${t("bu-neng-da-yu")}: ${max}${coin.code}`);
  if (!(amount >= min))
    return toast.text(`${t("bu-neng-xiao-yu")}: ${min}${coin.code}`);
  checkAuth(coin).then(async () => {
    toast.loading();
    const balance = await balanceStore.findGameBalance(coin);
    toast.close();
    if (!(amount <= balance!)) return toast.text(t("yu-e-bu-zu"));
    applyBuyGameBalance(coin, amount, currentOption!);
  });
}
/**购买理财产品,通过游戏余额 */
function applyBuyGameBalance(
  coin: CoinInfo,
  amount: number,
  option: HomeData.GoodsOption
) {
  showDialog({
    title: t("qing-que-ren"),
    message: `${amount}${coin.code}`,
  }).then(async () => {
    const res = await apiApplyBuyGameBalance({
      store_id: option.id,
      number: amount,
    });
    if (!res) return;
    removeCache("fundManage");
    router.push({ name: "buySuccess" });
  });
}
const currentCoinMin = computed(() => {
  return Number(currentOption.value?.min) / Number(goods.value?.price);
});
</script>

<template>
  <Rdialog ref="RdialogRef">
    <div class="auto-MT-md">
      <div class="C-success">
        {{ formatNumber(Number(currentOption?.multiple) * 100)
        }}<span class="T-S-lg">%</span>
      </div>
      <div class="T-S-sm MT-0 C-T3">
        {{ $t("can-kao") }}{{ currentOption?.day }}<span>{{ $t("tian") }}</span
        >{{ $t("shou-yi-shuai") }}
      </div>
      <RradioBtnGroup v-model="formData.optionIndex">
        <RradioBtn v-for="(option, index) in goods?.store" :value="index">
          <div v-if="option.is_anytime">{{ $t("sui-cun-sui-qu") }}</div>
          <div v-else>{{ option.day }}{{ $t("tian-li-cai") }}</div>
          <div class="MT-xs">
            {{ formatNumber(Number(option.multiple) * 100) }}<span>%</span>
          </div>
        </RradioBtn>
      </RradioBtnGroup>
      <div class="T-S-sm">{{ $t("tou-zi-jin-e") }}</div>
      <Ccard bg="var(--C-B2)" class="T-S-sm flex-J-SB">
        <VanField
          v-model="formData.amount"
          type="number"
          maxlength="20"
          :placeholder="`${$t('zui-di-tou-zi')}${formatNumber(currentCoinMin)}${
            currentCoin?.code
          }`"
        >
          <template #extra>
            <div
              @click="formData.amount = currentCoin?.balance?.toString() || ''"
              class="active C-M1"
            >
              {{ $t("zui-da") }}
            </div>
          </template>
        </VanField>
      </Ccard>
      <div class="flex-J-SB">
        <div class="T-S-sm C-T3">
          {{ $t("qian-bao-yu-e") }}
          <span class="C-T1">
            {{ formatNumber(currentCoin?.balance) }}
            <span>{{ currentCoin?.code }}</span>
          </span>
        </div>
        <div class="T-S-sm C-T3">
          <span>DAPP</span> {{ $t("yu-e") }}
          <span class="C-T1">
            {{ formatNumber(currentCoin?.gameBalance) }}
            <span>{{ currentCoin?.code }}</span>
          </span>
        </div>
      </div>
    </div>
    <template #footer>
      <Cgrid col="2" repeat="1fr">
        <VanButton @click="onSubmitBtn" color="var(--C-B5)" block>
          {{ $t("qian-bao-shen-gou") }}
        </VanButton>
        <VanButton @click="onSubmitBtnByGameBalance" color="var(--C-B5)" block>
          {{ $t("yueshen-gou") }}
        </VanButton>
      </Cgrid>
    </template>
  </Rdialog>
</template>

<style lang="less" scoped></style>
